package com.zhs.gccs.http;

import android.util.Log;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;


public class RequestBodyUpload extends RequestBody {
    private RequestBody requestBody;
    private String filename;
    private CommonCallback.OnProgressWithNameCallBack onProgressWithNameCallBack;
    private BufferedSink bufferedSink;

    public RequestBodyUpload(RequestBody requestBody, String filename, CommonCallback.OnProgressWithNameCallBack onProgressWithNameCallBack) {
        super();
        this.requestBody = requestBody;
        this.filename = filename;
        this.onProgressWithNameCallBack = onProgressWithNameCallBack;
    }

    @Override
    public long contentLength() throws IOException {
        return requestBody.contentLength();
    }

    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        synchronized (this) {
            if (bufferedSink == null) {
                bufferedSink = Okio.buffer(sink(sink));
            }
            requestBody.writeTo(bufferedSink);
            bufferedSink.flush();
        }
    }

    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            long bytesWritten = 0L;
            long contentLength = 0L;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                synchronized (this) {
                    super.write(source, byteCount);
                    if (contentLength == 0) {
                        contentLength = contentLength();
                    }
                    bytesWritten += byteCount;
                    Log.e("sc", "bytesWritten = " + bytesWritten + ", contentLength = " + contentLength);
                    onProgressWithNameCallBack.onProgress(filename, (float) bytesWritten / (float) contentLength);
                }
            }
        };
    }
}